function product() {
	this.totlePrice = 0;
	//产品对象
	this.products = [];
	//菜单对象
	this.meuns = [];
	//购物车对象
	this.outputinfo = []
}

//全局分类id 用作请求商品使用
var cateXId = null;

var perfix = "http://1.15.177.112:8080"

function car() {
	this.title = "";
	this.price = 0;
	this.img = '';
	this.num = 0;
}

var product = new product();

$("#mediaBody").on("click", function() {
	$("#toggleBody").css("display", "block");
	$("#sumX").text(1);
})
$("#toggleClose").on("click", function() {
	$("#toggleBody").css("display", "none");
})

$("#calcDeck").on("click", function() {
	$res = Number($("#sumX").text());
	if ($res <= 1) {
		return;
	}
	$("#sumX").text($res - 1);
})
$("#calcAdd").on("click", function() {
	$res = Number($("#sumX").text());
	$("#sumX").text($res + 1);
})

$openModel = null;
$imgName = null;
$itemId = null;

//------------- 点击+1按钮 -------------
$("#addCar").on("click", function() {
	$num = Number($("#sumX").text());
	$money = Number($("#priceToggle").text().split("¥")[1]);
	$title = $("#toggleTitle").text();
	$img = $imgName;

	var flag = true;
	for (i = 0; i < product.outputinfo.length; i++) {
		if (product.outputinfo[i].id == $itemId) {
			product.outputinfo[i].num += $num;
			flag = false;
		}
	}
	if (flag) {
		var car = {};
		car.img = $img;
		car.price = $money;
		car.title = $title;
		car.num = $num;
		car.id = $itemId;
		product.outputinfo.push(car);
	}
	product.totlePrice += $money;
	$("#totalPricr").text("总价：¥" + product.totlePrice.toFixed(2));
	if (isNaN($openModel.children().last().prev().text())) {
		$openModel.children().last().before('<button class="btn btn-info btn-desc">-</button><span id="sumOne">' + $num +
			'</span>');
		$("#badgeX").text(Number($("#badgeX").text()) + $num)

		//点击-1按钮
		$(".btn-desc").on("click", function() {
			$price = Number($(this).siblings(":first").text().split("¥")[1]);
			product.totlePrice -= $price;
			$("#totalPricr").text("总价：¥" + product.totlePrice.toFixed(2));
			$res = Number($(this).next().text()) - 1
			$("#badgeX").text(Number($("#badgeX").text()) - 1)
			$(this).next().text($res);
			for (i = 0; i < product.outputinfo.length; i++) {
				if (product.outputinfo[i].id == $itemId) {
					product.outputinfo[i].num -= $num;
					if (product.outputinfo[i].num == 0) {
						product.outputinfo.splice(i, 1);
					}
				}
			}
			if ($res < 1) {
				$(this).next().remove();
				$(this).remove();
			}
		})
	} else {
		$("#badgeX").text(Number($("#badgeX").text()) + $num)
		$openModel.children().last().prev().text(Number($openModel.children().last().prev().text()) + $num);
	}
	$("#toggleBody").css("display", "none");
})
//------------- 点击添加按钮 -------------


$("#calcBtn").on("click", function() {
	console.log(product.outputinfo)
	if (product.outputinfo.length == 0) {
		$("#carTabBody").children().remove()
		$("#carTabBody").append('<tr colspan="3"><td align="center">购物车空空如也</td></tr>');
		$("#toOrder").css("display", "none");
		return;
	}
	$("#carTabBody").children().remove();
	$("#toOrder").css("display", "block");

	for (i = 0; i < product.outputinfo.length; i++) {
		$("#carTabBody").append('<tr><td style="width: 20%;"><img src="' + product.outputinfo[i].img +
			'" class="media-img" /></td><td><p>名称：' + product.outputinfo[i].title + '</p><p>数量：' + product.outputinfo[i].num +
			'</p><p>单价：' + product.outputinfo[i].price + ' ¥</p><p>一共：' + Number(product.outputinfo[i].price) * Number(
				product.outputinfo[i].num) +
			' ¥</p></td><td><input type="checkbox" class="form-check-input" id="exampleCheck1"></td></tr>')
	}
})

// ------------- 点击生成订单 -------------
$("#toOrder").on("click", function() {
	$.ajax({
		url: perfix + "/order/getOrder",
		data: JSON.stringify(product.outputinfo),
		type: 'post',
		headers: {
		             'Authorization':localStorage.getItem("token")
		         },
		contentType: 'application/json',
		success: function(data) {
			$(window).attr('location', "./page/orderdesc.html?id="+data.data);
		}
	})
})
// ------------- 点击生成订单 -------------

// ------------- 页面初始化 -------------
$.ajax({
	headers: {
	             'Authorization':localStorage.getItem("token")
	         },
	url: perfix + "/category/list",
	data: '',
	type: 'post',
	contentType: 'application/json',
	success: function(data) {
		
		if(data.code == 10006){
			localStorage.clear();
			$(window).attr('location',"./page/login.html");
		}
		
		cateXId = data.data[0].id;
		getProduct(cateXId);
		for (var i = 0; i < data.data.length; i++) {
			product.meuns[i] = {
				"id": data.data[i].id,
				"categoryName": data.data[i].categoryName,
			}
			
		}
		for (i = 0; i < product.meuns.length; i++) {
			$("#v-pills-tab").append(
				'<a class="nav-link list-aX" id="v-pills-home-tab" data-toggle="pill" href="#v-pills-home">' + product.meuns[i].categoryName +
				'</a><input type="hidden" value="' + product.meuns[i].id + '">')
			cateXId = product.meuns[i].id;
		
		}
		$(".list-aX").on('click', function() {
			getProduct($(this).next().val());
		})

	}
})

// ------------- 页面初始化 -------------


// ------------- 根据分类id查询 -------------
function getProduct(cateId) {
	$("#v-pills-home").children().remove()
	product.products = [];
	console.log(cateId)
	var model = {
		"cateId": cateId,
		"page": 1,
		"size": 100
	}
	$.ajax({
		headers: {
		             'Authorization':localStorage.getItem("token")
		         },
		url: perfix + "/product/list",
		data: JSON.stringify(model),
		type: 'post',
		contentType: 'application/json',
		success: function(data) {
			if(data.code == 10006){
				localStorage.clear();
				$(window).attr('location',"./page/login.html");
			}
			
			for (var i = 0; i < data.data.records.length; i++) {
				product.products[i] = {
					"id": data.data.records[i].id,
					"title": data.data.records[i].productTitle,
					"productName": data.data.records[i].productName,
					"content": data.data.records[i].productDesc,
					"price": data.data.records[i].productPrice,
					"img": [data.data.records[i].productImg]
				}
			}
			for (i = 0; i < product.products.length; i++) {
				$("#v-pills-home").append('<div class="media"><span id="sumIndex" style="visibility:hidden">' + i +
					'</span><img src="' + product.products[i].img[0] +
					'" class="mr-3 media-img" alt="..."><div class="media-body" ><span id="sumIndex" style="visibility:hidden">' +
					i +
					'</span><h5 class="mt-0 font-weight-normal mediaX" id="titleAX" >' + product.products[i].productName +
					'</h5><span class="media-font mediaX">' + product.products[i].content +
					'</span><div class="d-flex justify-content-between opt-btn"><h4 class="font-weight-normal">¥' + product.products[
						i].price + '</h4><span id="sumIndex" style="visibility:hidden">' + i +
					'</span><span style="visibility:hidden">abc</span><button class="btn btn-info btn-add">+</button></div></div></div>'
				);

				$(".mediaX").unbind();
				//用户点开商品详情
				$(".mediaX").on("click", function() {
					console.log(2134);
					$openModel = $(this).siblings().last();
					$("#toggleBody").css("display", "block");
					$obj = product.products[Number($(this).siblings(":first").text())];
					$("#imgX").children().remove();
					$("#contentToggle").children().remove();
					$imgName = $obj.img[0];
					$itemId = $obj.id;
					for (i = 0; i < $obj.img.length; i++) {
						if (i == 0) {
							$("#imgX").append('<div  class="carousel-item active"><img src="' + $obj.img[i] +
								'" class="d-block w-100" alt="..."></div>');
						} else {
							$("#imgX").append('<div class="carousel-item"><img src="' + $obj.img[i] +
								'" class="d-block w-100" alt="..."></div>');
						}
					}
					$("#contentToggle").append('<h3 id="toggleTitle">' + $obj.title + '</h3><p>产品描述</p><p id="toggleContent">' +
						$obj
						.content + '</p>');
					$("#priceToggle").html("¥" + $obj.price);

				})

				$(".btn-add").unbind();
				// 页面点击+1
				$(".btn-add").on("click", function() {
					$price = Number($(this).siblings(":first").text().split("¥")[1]);

					productX = product.products[Number($(this).siblings(":first").next().text())];

					var flag = true;
					for (i = 0; i < product.outputinfo.length; i++) {
						if (product.outputinfo[i].id == productX.id) {
							product.outputinfo[i].num += 1;
							flag = false;
						}
					}
					if (flag) {
						var car = {};
						car.id = productX.id;
						car.img = productX.img[0];
						car.price = $price;
						car.title = productX.title;
						car.num = 1;
						console.log(car);
						product.outputinfo.push(car);
					}

					product.totlePrice += $price;
					$("#totalPricr").text("总价：¥" + product.totlePrice.toFixed(2));
					console.log($(this).prev().text())
					if (isNaN($(this).prev().text())) {
						console.log(123);
						$(this).before('<button class="btn btn-info btn-desc">-</button><span id="sumOne">' + 1 + '</span>');
						$("#badgeX").text(Number($("#badgeX").text()) + 1)

						$(".btn-desc").unbind()
						$(".btn-desc").on("click", function() {

							productX = product.products[Number($(this).siblings(":first").next().text())];
							$price = Number($(this).siblings(":first").text().split("¥")[1]);
							product.totlePrice -= $price;
							$("#totalPricr").text("总价：¥" + product.totlePrice.toFixed(2));
							console.log(Number($(this).next().text()));
							$res = Number($(this).next().text()) - 1;
							$("#badgeX").text(Number($("#badgeX").text()) - 1);
							$(this).next().text($res);
							for (i = 0; i < product.outputinfo.length; i++) {
								if (product.outputinfo[i].id == productX.id) {
									product.outputinfo[i].num -= 1;
									if (product.outputinfo[i].num == 0) {
										product.outputinfo.splice(i, 1);
									}
								}
							}
							if ($res < 1) {
								$(this).next().remove();
								$(this).remove();

							}
						})
					} else {
						$("#badgeX").text(Number($("#badgeX").text()) + 1)
						$(this).prev().text(Number($(this).prev().text()) + 1);
					}
				})

			}


		}
	})
}
// ------------- 根据分类id查询 -------------


// ------------- 主页加载js -------------
$(document).ready(function() {
	$bodyh = $(window).height(); //浏览器当前窗口文档body的高度
	$topnav = $("#topNav").outerHeight(true);
	$lastnav = $("#lastNav").outerHeight(true);
	$result = $bodyh - $topnav - $lastnav;
	console.log($bodyh);
	console.log($topnav);
	console.log($lastnav);
	$("#contentX").css("height", $result);
	$("#listColX").css("height", $result);
	$("#contentColX").css("height", $result);
	$("#listColX").css("background", "rgba(230,230,230,0.7)");
	$("#collapseBtnCalc").css("bottom", $lastnav)

	var userId = localStorage.getItem("userId");
	console.log(userId);
	if (userId == null) {
		$("#topUser").append(
			'<button type="button" class="btn btn-link">登录</button><button type="button" class="btn btn-link">注册</button>')
		$("#topUser").on('click', function() {
			$(window).attr('location', "./page/login.html");
		})
	} else {
		var username = localStorage.getItem("username");
		$("#topUser").append($(`
		<a herf="./page/user.html" type="button" class="btn btn-link">${username}</a>`))
		$("#topUser").on('click', function() {
			$(window).attr('location', "./page/user.html");
		})
	}

	// product.meuns = ["喜茶实验室", "当季限定", "人气必喝", "喜茶制冰", "热饮推荐", "果茶家族", "名茶/牛乳茶", "啵啵家族", "喜茶咖啡", "纯茶", "加料", "早餐组合"];

	// product.products = [{
	// 	"id": 1,
	// 	"title": "喜小瓶无糖气泡水",
	// 	"content": "口味升级，专注纯粹果香；容量升级，加量不加价；设计升级，重塑全新流畅瓶型。清新果香唤醒味蕾，纤维添加，不止含糖",
	// 	"price": "5.5",
	// 	"img": ["./image/WechatIMG33.jpeg", "./image/WechatIMG32.jpeg"]
	// }, {
	// 	"id": 2,
	// 	"title": "忙忙碌碌",
	// 	"content": "口味升级，专注纯粹果香；容量升级，加量不加价；设计升级，重塑全新流畅瓶型。清新果香唤醒味蕾，纤维添加，不止含糖",
	// 	"price": "5.5",
	// 	"img": ["./image/WechatIMG32.jpeg", "./image/WechatIMG33.jpeg"]
	// }, {
	// 	"id": 3,
	// 	"title": "喜小瓶无糖气泡水",
	// 	"content": "口味升级，专注纯粹果香；容量升级，加量不加价；设计升级，重塑全新流畅瓶型。清新果香唤醒味蕾，纤维添加，不止含糖",
	// 	"price": "5.5",
	// 	"img": ["./image/WechatIMG33.jpeg", "./image/WechatIMG33.jpeg"]
	// }, {
	// 	"id": 4,
	// 	"title": "喜小瓶无糖气泡水",
	// 	"content": "口味升级，专注纯粹果香；容量升级，加量不加价；设计升级，重塑全新流畅瓶型。清新果香唤醒味蕾，纤维添加，不止含糖",
	// 	"price": "5.5",
	// 	"img": ["./image/WechatIMG33.jpeg", "./image/WechatIMG33.jpeg"]
	// }, {
	// 	"id": 5,
	// 	"title": "喜小瓶无糖气泡水",
	// 	"content": "口味升级，专注纯粹果香；容量升级，加量不加价；设计升级，重塑全新流畅瓶型。清新果香唤醒味蕾，纤维添加，不止含糖",
	// 	"price": "17.9",
	// 	"img": ["./image/WechatIMG33.jpeg", "./image/WechatIMG33.jpeg"]
	// }]
})
// ------------- 主页加载js -------------
